package com.zfei.gfb.device.web.mvc;

import com.zfei.gfb.bean.Result;
import com.zfei.gfb.util.WebLogBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author fgh
 */
@RestControllerAdvice
public class ControllerAdviceHandler {

    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result handleException(HttpMessageNotReadableException ex) {
        return handle(ex, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(HttpMessageNotWritableException.class)
    @ResponseStatus(HttpStatus.EXPECTATION_FAILED)
    public Result handleException(HttpMessageNotWritableException ex) {
        return handle(ex, HttpStatus.EXPECTATION_FAILED);
    }

    @ExceptionHandler(HttpMediaTypeNotAcceptableException.class)
    @ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
    public Result handleException(HttpMediaTypeNotAcceptableException ex) {
        return handle(ex, HttpStatus.NOT_ACCEPTABLE);
    }

    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    public Result handleException(HttpMediaTypeNotSupportedException ex) {
        return handle(ex, HttpStatus.UNSUPPORTED_MEDIA_TYPE);
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    public Result handleException(HttpRequestMethodNotSupportedException ex) {
        return handle(ex, HttpStatus.METHOD_NOT_ALLOWED);
    }

    @ExceptionHandler(Throwable.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result handleException(Throwable ex) {
        return handle(ex, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    private Result handle(Throwable ex, HttpStatus status) {
        WebLogBean logBean = WebLogBean.getLogBean();
        logBean.setCode(status.value());
        logBean.setError(ex.getMessage());
        return new Result(status.value(), status.getReasonPhrase());
    }
}
